// config

var app =  
angular.module('app')
  .config(
    [        '$controllerProvider', '$compileProvider', '$filterProvider', '$provide',
    function ($controllerProvider,   $compileProvider,   $filterProvider,   $provide) {
        
        // lazy controller, directive and service
        app.controller = $controllerProvider.register;
        app.directive  = $compileProvider.directive;
        app.filter     = $filterProvider.register;
        app.factory    = $provide.factory;
        app.service    = $provide.service;
        app.constant   = $provide.constant;
        app.value      = $provide.value;
    }
  ])
  .config(['$uibTooltipProvider', function($uibTooltipProvider){
  	$uibTooltipProvider.options({appendToBody:true});
  }])
  .config(['uibDatepickerPopupConfig', function(uibDatepickerPopupConfig){
  	if(ISS.lang == 'zh'){
	  	uibDatepickerPopupConfig.clearText = '\u6E05\u9664';
	  	uibDatepickerPopupConfig.closeText = '\u5173\u95ED';
	  	uibDatepickerPopupConfig.currentText = '\u4ECA\u5929';
  	}else if(ISS.lang == 'en'){
  		uibDatepickerPopupConfig.clearText = 'Clear';
  		uibDatepickerPopupConfig.closeText = 'Close';
  		uibDatepickerPopupConfig.currentText = 'Today';
  	}
  }])
  .config(['$translateProvider', function($translateProvider){
    // Register a loader for the static files
    // So, the module will search missing translation tables under the specified urls.
    // Those urls are [prefix][langKey][suffix].
    $translateProvider.useLoader('$translateCustomerLoader', {
      prefix: ISS.getPath('/l10n/'),
      suffix: '.json'
    });
    //escape html XSS
    $translateProvider.useSanitizeValueStrategy('escape');
    // Tell the module what language to use by default
    $translateProvider.preferredLanguage('zh');
    // Tell the module to store the language in the local storage
    $translateProvider.useLocalStorage();
  }])
  .config(['$httpProvider', function($httpProvider){
  	//config http ajax set common
  	$httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
  	//set post
  	var postHeaher = $httpProvider.defaults.headers.post;
  	postHeaher['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
  	// add interceptor
  	$httpProvider.interceptors.push(function($q, $injector, $window, $rootScope, $translate, $timeout) {
  		//设置遮罩层
  		if ($rootScope.activeCalls == undefined) {
            $rootScope.activeCalls = 0;  
        }
        var errorDialog = null;
        //处理Jquery的ajax错误
        $(document)
		.ajaxSend(function(event,xhr,options) {
			//autoMask显示遮罩层
			if(options.autoMask !== false){
				$timeout(function(){
					$rootScope.activeCalls += 1;
				});
			}
		})
		.ajaxSuccess(function(event, status, settings) {
			$timeout(function(){
				if($rootScope.activeCalls > 0){
					$rootScope.activeCalls -= 1;
				}
			});
		})
        .ajaxError(function(event, status, settings, errorThrown) {
        	$timeout(function(){
				if($rootScope.activeCalls > 0){
					$rootScope.activeCalls -= 1;
				}
			});
			var data = status.responseJSON;
			
			$injector.get("LoginService").notify(data, status.status);
		});
		return {
			request: function(config) {
				var contentType = config.headers["Content-Type"];
				//form data parse data to string
				if(config.contentType == 'json'){
					config.headers["Content-Type"] = 'application/json; charset=UTF-8';
					if(angular.isUndefined(config.data) || config.data == null){
						config.data = {};
					}
				}else if(angular.equals(contentType, "application/x-www-form-urlencoded; charset=UTF-8")){
					if(angular.isDefined(config.data) && config.data != null){
						config.data = angular.element.param(config.data);
					}
				}
				//autoMask显示遮罩层
				if(config.autoMask !== false){
					$rootScope.activeCalls += 1;
				}
				return config;
			},
			requestError: function(rejection){
				if($rootScope.activeCalls > 0){
					$rootScope.activeCalls -= 1;
				}
				return $q.reject(rejection);
			},
			response: function(resp) {
				var deferred = $q.defer();
				if($rootScope.activeCalls > 0){
					$rootScope.activeCalls -= 1;
				}
				if(angular.isObject(resp.data)){
					//格式化为json字符串
					var data = angular.toJson(resp.data);
					if(data.code && data.code != '99006'){
						resp.data = angular.fromJson(data.replace(/&lt;/g, '<').replace(/&gt;/g, '>'));
					}
					if(resp.data.code && resp.data.success === false){
						var dialogs = $injector.get("dialogs");
						if(resp.data.code == '00013'){
							resp.data.description = resp.data.msg = ISS.getMessage('error.ref.' + resp.data.msg);
						}
						errorDialog = dialogs.notify(resp.data);
						errorDialog.closed.then(function(){
							errorDialog = null;
						});
						deferred.reject(resp.data);
					}else{
						deferred.resolve(resp);
					}
				}else{
					deferred.resolve(resp);
				}
				return deferred.promise;
			},  
            responseError: function (rejection) {
                if($rootScope.activeCalls > 0){
					$rootScope.activeCalls -= 1;
				}
                //处理Session超时
                var data = rejection.data;
				var config = rejection.config;
                
				$injector.get("LoginService").notify(data, rejection.status, config);

                return $q.reject(rejection);
            }  
		};
	});
  }]);